package logic

import (
	"context"
	"edu/edurpc/edurpc"
	"edu/edurpc/internal/svc"
	"edu/models/cache"
	"edu/models/mysql"
	"fmt"
	"math/rand"

	"github.com/zeromicro/go-zero/core/logx"
)

type LoginLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewLoginLogic(ctx context.Context, svcCtx *svc.ServiceContext) *LoginLogic {
	return &LoginLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *LoginLogic) Login(in *edurpc.LoginRequest) (*edurpc.LoginResponse, error) {
	smsCode, _ := cache.Rdb.Get(l.ctx, "smsCode_"+in.Account).Result()
	if in.SmsCode != smsCode {
		return nil, fmt.Errorf("验证码错误")
	}
	var user mysql.User
	mysql.DB.Where("account = ?", in.Account).First(&user)
	if user.ID == 0 {
		user = mysql.User{
			Account:  in.Account,
			Password: in.Password,
			NickName: fmt.Sprintf("游客_%d", rand.Intn(10000)),
			Image:    "https://gitee.com/static/images/logo-black.svg?t=158106664",
		}
		mysql.DB.Create(&user)
	} else {
		if user.Password != in.Password {
			return nil, fmt.Errorf("密码错误")
		}
	}
	return &edurpc.LoginResponse{
		UserId: int64(user.ID),
	}, nil
}
